// pages/luck/luck.js
import Router from '../../utils/router.js';
import authorize from '../../utils/authorize.js'
import ext from '../../utils/login'
import prize from '../../services/luck.js';
import Record from '../../services/record-stat';
import service_conch from '../../services/conch';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tab: {
      tab: 1
    },
    store_id: null, //店铺id
    user_id: '', //用户id
    scrolltop: '', //滚动条高度
    shougui: false,
    showanni: false,
    shownull: false,
    showbk: false, //中奖为贝壳的提示
    showcard: false, //中奖为优惠券的提示
    showmoney:false,//中奖位红包人民币
    lucking: false, //正在转动抽奖
    ok: false, //首次分享成功
    exchange: false, //兑换抽奖弹框
    user_cunch_num: '', //持有的贝壳数

    sharemail: '', //分享成功后的提示语言
    types: '', //弹出框是贝壳还是优惠券
    conch_num: '', //抽中的贝壳数
    coupons_num: '', //抽中的优惠券金额
    valid_day_format: '', //优惠券的过期时间
    full: '', //优惠券减
    luckmoney:'',//抽到的红包价格
    animationData: '', //动画
    off: 1, //禁止反复点击
    quan: 0, //转的圈数
    sudo: 50, //初始转动的速度
    kaishi: '', //定时器
    last: false, //监控最终圈数后停止
    lucknum: null, //幸运数字
    value: 0, //奖金
    count: 0, //可抽奖次数
    shouquan: false, //授权信息
    showbtns: false, //默认是false 点击授权的信息
    change_num: '', //兑换抽奖次数
    check_share: false, //false or ture 是否分享了
    today_order_num: '', //false or ture 是否下过单
    step: 0, //是否进行了步数兑换贝壳
    sign: 0, //是否邀请了还有签到
    share_draw:0,//是否进行了浏览商品对奖品
    isFirst: true,
    timebox: '', //定时器
    times: 3, //3分钟
    isthree: false, //分享后三分钟才增加机会
    hottodyList: [],//贝壳当钱花
    loadBloon: true,
    endBloon: true,
    pages: 0,
    noMore: true,
    dui:false,
    transmit: { //formid
      style: 'position:absolute;width:100%;height:100%;background:red;opacity:0;',
      value: ''
    },
    luck: [{
      id: 1,
      bg: 1
    },
    {
      id: 2,
      bg: 1
    },
    {
      id: 3,
      bg: 1
    },
    {
      id: 4,
      bg: 1
    },
    {
      id: 5,
      bg: 1
    },
    {
      id: 6,
      bg: 1
    },
    {
      id: 7,
      bg: 1
    },
    {
      id: 8,
      bg: 1
    },
    {
      id: 9,
      bg: 1
    },
    {
      id: 10,
      bg: 1
    },
    {
      id: 11,
      bg: 1
    },
    {
      id: 12,
      bg: 1
    }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this;
    let user_info = wx.getStorageSync('user_info')
    _this.setData({
      isFirst: false,
      ok: false,
      options,
      user_id: user_info.id
    })
    if (options.store_id) {
      _this.setData({
        store_id: options.store_id
      })
    }
    if (user_info.info_authorize == 1) {
      _this.creatHtml();
      _this.getPrizeTask();
      _this.setData({
        showbtns: false,
        shouquan: true
      })
    } else {
      _this.setData({
        shouquan: false,
        count: 1,
        showbtns: true
      })
    }
    _this.setData({
      hottodyList:[],
      endBloon: true,
      loadBloon: true
    })
    this.createHot(1);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  //得到任务详情
  getPrizeTask() {
    let _this = this;
    let params = {}
    prize.getPrizeTask(params, res => {
      console.log(res)
      if (res.code == 1) {
        _this.setData({
          change_num: res.data.change_num,
          check_share: res.data.check_share,
          today_order_num: res.data.today_order_num,
          step: res.data.step,
          sign: res.data.sign,
          share_draw: res.data.share_draw
        })
      }
    })
  },
  creatHtml() {
    var _this = this;
    var params = {
      prize_date: "fifthPrize"
    };
    prize.prizes(params, res => { //开始抽奖
      if (res.code == 1) {
        _this.setData({
          count: res.data.count,
          user_cunch_num: res.data.user_cunch_num
        })
      } else {
        _this.setData({
          count: 0
        })
      }
    })
  },
  getUserInfos(e) { //授权
    let d = e.detail;
    console.log(e)
    var _this = this;
    if (d.errMsg == 'getUserInfo:ok') {
      ext.getUserInfo(d, b => {
        if (b) {
          _this.setData({
            showbtns: false,
            shouquan: true
          })
          _this.creatHtml();
        }
      });
    }
  },
  startLuck(e) {
    var _this = this;
    if (this.data.shouquan) {
      console.log('第一次')
      if (this.data.off == 1) {
        console.log('这是off次数')
        _this.setData({
          off: 2
        })
        var params = {
          prize_date: 'fifthPrize'
        };
        prize.prize(params, res => { //开始抽奖
          if (res.code == 1) {
            if (_this.data.count != 0) {
              _this.choujiang(res.data.prize)
            }
            _this.setData({
              value: res.data.prize.value,
              count: res.data.count,
              lucking: true
            })
          } else if (res.code == 0) {
            _this.setData({
              shownull: true,
              off: 1
            })
          }
        })
      }
    }
  },
  choujiang(data) { //抽奖动画
    var _this = this;
    console.log(data)
    var luckid = '';
    var types = '';
    var conch_num = '';
    var coupons_num = '';
    var valid_day_format = '';
    var full = '';
    var money='';
    if (data.prize_type == 'conch' && data.name == '抽奖获得50贝壳') {
      luckid = 11;
      types = 1;
      conch_num = 50;
    } else if (data.prize_type == 'conch' && data.name == '抽奖获得20贝壳') {
      luckid = 3;
      types = 1;
      conch_num = 20;
    } else if (data.prize_type == 'conch' && data.name == '抽奖获得5贝壳') {
      luckid = 6;
      types = 1;
      conch_num = 5;
    } else if (data.prize_type == 'conch' && data.name == '抽奖获得10贝壳') {
      luckid = 12;
      types = 1;
      conch_num = 10;
    } else if (data.prize_type == 'conch' && data.name == '抽奖获得100贝壳') {
      luckid = 9;
      types = 1;
      conch_num = 100;
    } else if (data.prize_type == 'coupons' && data.name == '抽奖获得5元优惠券') {
      luckid = 1;
      types = 2;
      coupons_num = 5;
      full = data.coupons_info.full;
      valid_day_format = data.coupons_info.valid_day_format;
    } else if (data.prize_type == 'coupons' && data.name == '抽奖获得2元优惠券') {
      luckid = 4;
      types = 2;
      coupons_num = 2;
      full = data.coupons_info.full;
      valid_day_format = data.coupons_info.valid_day_format;
    } else if (data.prize_type == 'coupons' && data.name == '抽奖获得10元优惠券') {
      luckid = 7;
      types = 2;
      coupons_num = 10;
      full = data.coupons_info.full;
      valid_day_format = data.coupons_info.valid_day_format;
    } else if (data.prize_type == 'coupons' && data.name == '抽奖获得1元优惠券') {
      luckid = 10;
      types = 2;
      coupons_num = 1;
      full = data.coupons_info.full;
      valid_day_format = data.coupons_info.valid_day_format;
    } else if (data.prize_type == 'money'){
      luckid = 8;
      types = 3;
      money=(Number(data.value)/100).toFixed(2);
    }
    _this.setData({
      lucknum: luckid,
      types: types,
      conch_num: conch_num,
      coupons_num: coupons_num,
      valid_day_format: valid_day_format,
      full: full,
      luckmoney:money
    })
    var num = 0;
    var quanshu = 0;
    test()

    function test() {
      _this.data.kaishi = setInterval(function () {
        let newluck = _this.data.luck;
        for (var i = 0; i < newluck.length; i++) { //初始化所有id
          newluck[i].bg = 1
        }
        _this.setData({
          luck: newluck
        })
        var bg = 'luck[' + num + '].bg'
        _this.setData({
          [bg]: 2
        })
        if (_this.data.last && _this.data.luck[num].id == _this.data.lucknum) { //清除定时器最终停留的块        
          _this.setData({
            lucking: false
          })
          clearInterval(_this.data.kaishi)
          setTimeout(function () {
            _this.animatetoast() //执行动画
          }, 600)
        }
        num++
        if (num == 12) {
          quanshu++
          _this.setData({
            quan: quanshu
          })
          if (_this.data.quan == 2) {
            clearInterval(_this.data.kaishi)
            _this.setData({
              sudo: 100
            })
            test()
          } else if (_this.data.quan == 3) {
            clearInterval(_this.data.kaishi)
            _this.setData({
              sudo: 180
            })
            test();
          } else if (_this.data.quan == 4) {
            clearInterval(_this.data.kaishi)
            _this.setData({
              sudo: 280,
              last: true
            })
            test();
          }
          num = 0
        }
      }, _this.data.sudo)
    }

  },
  animatetoast() { //弹出动画
    var _this = this;
    if (this.data.count >= 1) {
      if (this.data.types == 1) {
        _this.setData({
          showbk: true
        })
      } else if (this.data.types == 2) {
        _this.setData({
          showcard: true
        })
      } else if (this.data.types == 3){
        _this.setData({
          showmoney: true
        })
      }
    } else if (this.data.count == 0) { //最终次
      if (this.data.types == 1) {
        _this.setData({
          showbk: true
        })
      } else if (this.data.types == 2) {
        _this.setData({
          showcard: true
        })
      } else if (this.data.types == 3) {
        _this.setData({
          showmoney: true
        })
      }
    }
  },
  hideMask(e) {
    var _this = this;
    let mail = e.currentTarget.dataset.mail;
    _this.letRest();
    if (mail != 'no') {
      _this.startLuck()
    }

  },
  //20贝壳兑换一次抽奖机会
  exChange() {
    this.setData({
      exchange: true
    })
  },
  //20贝壳兑换一次机会
  goExchange() {
    if(this.data.dui){
      return false;
    }
    this.setData({
      dui:true
    })
    let params = {};
    let _this = this;
    prize.conchToPrizenum(params, res => {
      if (res.code == 1) {
        _this.letRest();
        _this.setData({
          exchange: false
        })
        _this.creatHtml();
        _this.startLuck();
        _this.getPrizeTask();
        _this.setData({
          dui:false
        })
      } else {
        _this.setData({
          dui: false
        })
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  //初始化数据
  letRest(){
    let _this=this;
    let newluck = _this.data.luck;
    for (var i = 0; i < newluck.length; i++) {
      newluck[i].bg = 1
    }
    _this.setData({ //初始化所有数据 抽奖完毕
      showcard: false,
      shownull: false,
      showbk: false,
      showmoney: false,
      luckmoney: '',
      conch_num: '',
      coupons_num: '',
      valid_day_format: '',
      full: '',
      types: '',
      off: 1,
      last: false,
      quan: 0,
      sudo: 50,
      luck: newluck,
      lucknum: 0,
      value: 0
    })
  },
  hideTip() {
    this.setData({ //隐藏没有抽奖机会
      shownull: false
    })
  },
  showtips() { //没有抽奖机会了
    this.setData({
      shownull: true
    })
  },
  routerStore() { //去到店铺页
    if (this.data.lucking) {
      return false
    }
    var store = this.data.store_id,
      opt = '';
    if (store) {
      opt = `store_id=${store}`
    }
    Router.go('store', opt, 'reLaunch');
  },
  hideFina() { //最后一次点击
    this.setData({
      off: 1
    })
  },
  //抽奖领钱（付钱）
  wxPaymoney(){
    let params={};
    let _this=this;
    prize.wxPayMoneyToCustomer(params,res=>{
      wx.showToast({
        title: '领取成功',
        icon: 'none'
      })
      _this.letRest()
    })
  },
  getH(){
    console.log(this.data.showmoney)
  },
  // 点击邀请小伙伴记录
  sharefriend: function () {
    let that = this;
    let user_info = wx.getStorageSync('user_info')
    let params = {
      name: "ltxx_buyer",
      page: 'luck',
      productid: '',
      button_name: 'choujianginvite',
      userid: user_info.id,
      storeid: user_info.lastView.seid,
      act: 'click',
      env: getApp().globalData.env
    }
    Record.recordstat(params, function () { });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var _this = this;
    // clearInterval(_this.data.kaishi)

    clearTimeout(_this.data.timebox)
    if (!_this.data.isFirst) {
      let p = getCurrentPages().pop()
      p.onLoad({
        options: _this.data.options
      });
    }
    if (this.data.isthree) {
      let params = {
        prize_date: 'fifthPrize'
      }
      prize.saveSharePrize(params, res => {
        console.log(res)
        if (res.code == 1) {
          _this.setData({
            shownull: false,
            isthree: false
          })
          // wx.showToast({
          //   title: '分享成功，获得一次抽奖机会',
          //   icon: 'none'
          // })
          _this.getPrizeTask();
          _this.creatHtml();
        } else {
          _this.setData({
            isthree: false
          })
            // wx.showToast({
            //   title: '分享成功～',
            //   icon: 'none'
            // })
        }
      })
    }
    this.setData({
      times: 3
    })
  },
  //隐藏兑奖弹框
  hideExchange() {
    this.setData({
      exchange: false
    })
  },
  //去到任务中心
  goRenwu() {
    console.log(1)
    console.log(this.data.change_num)
    if (this.data.user_cunch_num < 30 && this.data.change_num <10) {
      wx.showModal({
        title: '您的贝壳余额不足',
        content: '快去赚贝壳吧！',
        confirmText: '赚贝壳',
        success(res) {
          if (res.confirm) {
            Router.go('dailytasks', '', 'navigateTo')
          }
        }
      })
    } else if (this.data.change_num==10){
        wx.showToast({
          title: '每天最多兑换10次哟',
          icon:'none',
          duration:1400
        })
    }
  },
  //去到步数兑换贝壳页面
  routerStep() {
    let store_id = wx.getStorageSync('user_info').lastView.seid;
    console.log(store_id)
    Router.go('sports', `store_id=${store_id}`);
    this.setData({
      shownull: false
    })
  },
  //去到邀请好友签到页面
  routerFriend() {
    Router.go('shellForm', ``);
    this.setData({
      shownull: false
    })
  },
  //查看h5活动页面规则
  routerH5() {
    let url = encodeURIComponent('https://kpxd.zhengdianhaohuo.com/h5/#/active/win3_957')
    Router.go('web', `url=${url}`)
  },
  //贝壳当钱花
  createHot(page) {
    let _this = this;

    let param = {
      limit: 20,
      offset: page
    };
    service_conch.getConchGoods(param, res => {
      if (res.code == 200) {
        let hottodyList = _this.data.hottodyList.concat(res.data.list);
        for (var i = 0; i < hottodyList.length; i++) {
          let goods_pic = [];
          goods_pic[0] = {
            url: hottodyList[i].src
          }
          hottodyList[i].goods_pic = goods_pic
        }
        _this.setData({
          hottodyList: hottodyList,
          pages: page + 1,
          endBloon: true,
        })
        if (hottodyList.length >= res.data.count) {
          _this.setData({
            loadBloon: false,
            noMore: false
          })
        }
      }
    })
  },
  //监听页面高度
  scrollTimer: null,
  onPageScroll: function (e) {
    let that = this;
    if (that.scrollTimer) {
      clearTimeout(that.scrollTimer)
    };
    that.scrollTimer = setTimeout(() => {
      that.setData({
        scrolltop: e.scrollTop
      })
    }, 500);
  },
  //去到浏览商品列表页
  goLiulan(){
    let luckDraw='';
    if (this.data.share_draw){
      luckDraw ='noDraw';
    }else{
      luckDraw ='luckDraw';
    }
    Router.go('specialhome', `entrance=${luckDraw}`)
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function (e) {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function (e) {
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this;
    if (that.data.loadBloon && that.data.endBloon) {
      that.setData({
        endBloon: false
      })
      that.createHot(that.data.pages);
    }
  },
  //倒计时
  isThree() {
    let _this = this;
    _this.data.times--;
    this.data.timebox = setTimeout(function () {
      console.log(_this.data.times)
      if (_this.data.times == 0) {
        _this.setData({
          isthree: true
        })
        clearTimeout(_this.data.timebox)
      } else {
        _this.isThree();
      }
    }, 1000)
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let user_id = wx.getStorageSync("user_info").id
    let params = {
      prize_date: 'fifthPrize'
    }
    var _this = this;
    if (wx.getStorageSync("user_info").info_authorize == 1) {
      _this.isThree();
    }
    if (res.form === 'button') {
      console.log(res.target)
    }
    var id = this.data.store_id;
    var paths = '';
    if (id != null) {
      paths = 'pages/store/index?to=' + encodeURIComponent('/pages/luck/luck') + '&store_id=' + id + '&sharerecord=luckcard' + '&user_id=' + user_id
    } else {
      paths = 'pages/store/index?to=' + encodeURIComponent('/pages/luck/luck') + '&sharerecord=luckcard' + '&user_id=' + user_id
    }
    let luckmail = ['冲鸭！没有套路！100%中奖！最高50元现金红包~', '万水千山总是情，现金红包行不行！', '0元免费抽现金，躺赚1亿不是梦！', '福利来了！免费抽奖！现金送不停！', '该领钱时就领钱！', '洛阳亲友如相问，就说我在抽现金！','点我！点我！这可能是你距离暴富最近的一次！'];
    let mail = luckmail[Math.floor((Math.random() * luckmail.length))];
    return {
      title:mail,
      path: paths,
      imageUrl: 'https://kpxd.zhengdianhaohuo.com/kpxd_mp/asset/luck/millons.png'
    }
  }
})